package engine.ui
{
	import engine.newUi.WhisperLogic;
	import engine.ui.lite.BaseUI;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	import flash.utils.Dictionary;
	
	import newx.StageInfo;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.control.button.NxButton;
	import newx.com.control.group.NxViewGroup;
	import newx.com.control.text.NxLabel;
	import newx.utils.MemoryOptimise;
	
	public class FaceIconViewUI extends BaseUI
	{
		public var ViewBack		:MovieClip;
		public var faceIconGroup	:NxViewGroup;
		public var nextPage		:NxButton;
		public var prePage			:NxButton;
		public var pageLabel		:NxLabel;
		public var pageBack		:MovieClip;
		//静态数组，存放显示图标
		private static var _myPicData		:Array;
		//当前页与总页数
		private var _currentPage			:int;
		private var _totalPage				:int;
		private var _viewGroupNum			:int;
		private var _maxItem				:int
		
		private var iconArray		:Array;
		
		private var _callBackFun:Function;
		
		public static var faceIconList	:Dictionary = new Dictionary( true );;
		
		private var _showBtn		:DisplayObject;
		
		private static var _self	:FaceIconViewUI;

		public function FaceIconViewUI(popupUI:Boolean=true)
		{
			super(false);
		}
		
		public static function getInstance():FaceIconViewUI
		{
			if(_self	==	null)
			{
				_self	=	new FaceIconViewUI();
			}
			return _self;
		}
		
		override public function Init() : void
		{
			_myPicData		=	[];
			iconArray		=	[];
			_viewGroupNum	=	faceIconGroup.row * faceIconGroup.col;
			iconArray	=	StaticIni.getIniVar("FaceIconList", "listArray").split(",");
		}
		
		public  function borrowFaceIcon( url : String ):MovieClip
		{
			var mc : MovieClip;
			
			if( null == faceIconList[url] )
			{
				faceIconList[url] = [];
			}
			
			if( 0 == faceIconList[url].length )
			{
				mc	=	ResManager.newResClass(url) as MovieClip;
			}else
			{
				mc	=	faceIconList[url].shift();
			}
			if( null != mc)
			{
				mc.play();
				mc.mouseChildren = mc.mouseEnabled = false;
			}
			
			return mc;
		}
		
		
		public function returnFaceIcon( url : String, faceIcon : MovieClip ):void
		{
			MemoryOptimise.stopMovie( faceIcon );
			
			if( null == faceIconList[url] )
			{
				faceIconList[url] = [];
			}
			
			if( faceIconList[url] > 20 )return;
			
			faceIconList[url].push( faceIcon );
		}
		public function addStageEvent():void
		{
			StageInfo.stage.addEventListener(MouseEvent.CLICK, onHideViewBox);
		}
		public function removeStageEvent():void
		{
			StageInfo.stage.removeEventListener(MouseEvent.CLICK, onHideViewBox);
		}
		private function loadFaceIcon( val : String ):MovieClip
		{
			var mc : MovieClip;
			
			if( !ResManager.isResHave( val ))
			{
				ResManager.loadRes(val, val, onComplete );
			}else
			{
				mc = ResManager.getResContentCopy( val ) as MovieClip;
			}
			
			function onComplete( val:DisplayObject,pList:Array = null ):void
			{
				mc	=	val as MovieClip;
			}
			return mc;
		}
		private function loadFaceIconBefore():void
		{
			iconArray	=	StaticIni.getIniVar("FaceIconList", "listArray").split(",");
			if(iconArray.length == 0 || iconArray == null)
			{
				return;
			}
			else
			{
				for(var i:int = 0; i < iconArray.length ; i ++)
				{
					var iconID	:String		=	iconArray[i];
					//获取对应的icon
					var iconObj	:Object		=	StaticIni.getIniObj(iconID);
					var imgUrl	:String		=	"res/swf/faceIcon/"+iconObj["photo"]+".swf";
					borrowFaceIcon(imgUrl);
					ResManager.loadRes(imgUrl, imgUrl, onComplete, [imgUrl] );
				}
				function onComplete( val:DisplayObject,pList:Array = null ):void
				{
					returnFaceIcon( pList[0], val as MovieClip);
				}
			}
		}
		private function readIconList():void
		{
			//根据取模的方式来确定是否要对当前总页数去减1
			
			if((iconArray.length % _viewGroupNum) > 0){
				_totalPage		=	Math.floor(iconArray.length / _viewGroupNum);
			}else
			{
				_totalPage		=	Math.floor(iconArray.length / _viewGroupNum) -1;
			}
			showPageNum();
			checkPage();
			addIcon();
		}
		
		/**
		 * 添加表情图标 
		 */		
		private function addIcon():void
		{
			removImage()
			var index:int	=	0;
			for(var i:int  = _currentPage * _viewGroupNum;	i < _maxItem;	i++)
			{
				//图骗ID号
				var iconID	:String		=	iconArray[i]
				//获取对应的icon
				var iconObj	:Object		=	StaticIni.getIniObj(iconID);
				//获取图片填充对象
				var itemMC	:MovieClip 	=	faceIconGroup.getItemByIndex(index);
				//获取图片路径
				var imgUrl	:String		=	iconObj["photo"];
				
				//检查是否以加载过相应的icon
				var addNxClip:MovieClip	=	checkData(imgUrl)
				if(addNxClip == null){
					var img		:MovieClip		=	ResManager.newResClass(imgUrl) as MovieClip;
					img.x 						=	9	+	16;
					img.y						=	9	+	16;
					itemMC["data"]				=	iconObj;
					itemMC.addChild(img);
					MemoryOptimise.stopMovie(img);
					_myPicData.push([imgUrl,img])
				}else{
					itemMC.addChild(addNxClip);
					MemoryOptimise.stopMovie(addNxClip);
					itemMC["data"]			=	iconObj;		
				}
				index++;
			}
		}
		/**
		 * 检测当前加载的图是否加载过了 
		 * @param val
		 * @return 
		 * 
		 */		
		private function checkData(val:String):MovieClip
		{
			var tempNcClip:MovieClip	=	null;
			for each (var picData:Array in _myPicData)
			{
				if(picData[0] == val){
					tempNcClip	=	picData[1];
					return tempNcClip;
				}
			}
			return tempNcClip;
		}
		/**
		 * 判读当前循环的最大数
		 */		
		private function checkPage():void
		{
			//当前的起始指针
			var starIndex:int 	=	_viewGroupNum * ( _currentPage + 1 );
			if(starIndex  > iconArray.length){			
				_maxItem	=	iconArray.length;	
			}else{
				_maxItem	=	starIndex;
			}
		}
		
		/**
		 * 显示当前页码 
		 * 判断按钮装态
		 */		
		private function showPageNum():void
		{
			prePage	.enabled	=	true;
			nextPage	.enabled	=	true;
			
			if(_currentPage >= _totalPage){
				nextPage.enabled = false;
			}
			
			if(_currentPage == 0){
				prePage.enabled = false;
			}
			pageLabel.htmlText	=	(_currentPage+1) + "/" + (_totalPage +1)
		}
		/**
		 * 清除图片 
		 */		
		private function removImage():void
		{
			for(var i:int = 0;	i < _viewGroupNum;	i++)
			{
				//获取装备对象
				var itemMC	:MovieClip 	=	faceIconGroup.getItemByIndex(i);
				while(itemMC.numChildren > 1){
					var tempIconMc:MovieClip	=	itemMC.getChildAt(1) as MovieClip;
					MemoryOptimise.stopMovie(tempIconMc);
					//FaceIconViewUI.getInstance().returnFaceIcon(tempIconMc["iconName"],tempIconMc as MovieClip)
					itemMC.removeChild(tempIconMc);
				}
				itemMC["data"] = null;
			}

		}
		
		private function rollOverHandle(e:MouseEvent):void
		{
			var itemMC:MovieClip	=	e.currentTarget as MovieClip;
			var data :Object		=	itemMC.data;
			if(	null	==	data)	return;
			var icon:MovieClip	=	itemMC.getChildAt(1) as MovieClip;
			(icon).play();
		}
		
		private function rollOutHandle(e:MouseEvent):void
		{
			var itemMC:MovieClip	=	e.currentTarget as MovieClip;
			var data :Object		=	itemMC.data;
			if(	null	==	data)	return;
			var icon:MovieClip	=	itemMC.getChildAt(1) as MovieClip;
			MemoryOptimise.stopMovie(icon);
		}
		private function clickHandle(e:MouseEvent):void
		{
			var tempMc:MovieClip	=	e.currentTarget as MovieClip;
			var iconObj:Object		=	tempMc["data"];
			if(iconObj != null)
			{
				_callBackFun.call(null,iconObj["key"]);
			}
			if(WhisperLogic.getInstance().ui.created)
			{
				var val:int =WhisperLogic.getInstance().ui.inputTxt1.maxChars-WhisperLogic.getInstance().ui.inputTxt1.text.length;
				WhisperLogic.getInstance().ui.textLabel.htmlText =StaticIni.getSwfLangStrVar("UIString_1000109",[val]);
			}
		}
		private function pageClickHandle(e:MouseEvent):void
		{
			switch(e.currentTarget)
			{
				case prePage:
					_currentPage--;

					break;
				case nextPage:
					_currentPage++;
					break;
				
			}
			checkPage();
			addIcon();
			showPageNum();
		}
		private function onHideViewBox(e:MouseEvent):void
		{
			if(this.contains(e.target as DisplayObject))return;
			
			if( e.target == _showBtn) return;
			
			if(this.created)
			{
				this.hide()
			}
		}
		private function addListent():void
		{
			faceIconGroup.addItemsEvent(MouseEvent.ROLL_OVER,rollOverHandle);
			faceIconGroup.addItemsEvent(MouseEvent.ROLL_OUT,rollOutHandle);
			faceIconGroup.addItemsEvent(MouseEvent.CLICK,clickHandle);
			prePage.addEventListener(MouseEvent.CLICK,pageClickHandle);
			nextPage.addEventListener(MouseEvent.CLICK,pageClickHandle);

		}
		private function removeListent():void
		{
			faceIconGroup.removeItemsEvent(MouseEvent.ROLL_OVER,rollOverHandle);
			faceIconGroup.removeItemsEvent(MouseEvent.ROLL_OUT,rollOutHandle);
			faceIconGroup.removeItemsEvent(MouseEvent.CLICK,clickHandle);
			prePage.removeEventListener(MouseEvent.CLICK,pageClickHandle);
			nextPage.removeEventListener(MouseEvent.CLICK,pageClickHandle);

		}
		override protected function BeforeShow():void
		{
			readIconList();
			addListent()
		}
		

		/**点击图标时的回调函数*/
		public function set callBackFun(value:Function):void
		{
			_callBackFun = value;
		}

		public function set showBtn(value:DisplayObject):void
		{
			_showBtn = value;
		}


	}
}